package com.ywgt.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.ywgt.pojo.OssEntity;
import com.ywgt.service.AliossService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.UUID;
@Service
public class AliossServiceImpl implements AliossService , InitializingBean {
    @Autowired
    private OssEntity ossEntity;

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(ossEntity);
        this.endpoint=ossEntity.getEndpoint();
        this.accessKeyId=ossEntity.getAccessKeyId();
        this.accessKeySecret=ossEntity.getAccessKeySecret();
        this.bucketName=ossEntity.getBucketName();
    }

    @Override
    public String upload(MultipartFile file) {
        String uploadUrl=null;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        if(!ossClient.doesBucketExist(bucketName)){
            ossClient.createBucket(bucketName);
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
        }
        String originalFilename = file.getOriginalFilename();
        String datePath = DateTime.now().toString("yyyy/MM/dd");
        String random = UUID.randomUUID().toString().replaceAll("-", "");
        String filetype=originalFilename.substring(originalFilename.lastIndexOf("."));
        String path=datePath+"/"+random+filetype;
        try {
            InputStream inputStream = file.getInputStream();
            ObjectMetadata metadata=new ObjectMetadata();
            String type = getcontentType(filetype);
            metadata.setContentType(type);
            metadata.setObjectAcl(CannedAccessControlList.PublicRead);
            ossClient.putObject(bucketName,path,inputStream,metadata);
            ossClient.shutdown();
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            uploadUrl = ossClient.generatePresignedUrl(bucketName, path, expiration).toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return uploadUrl.substring(0,uploadUrl.indexOf("?"));
    }

    @Override
    public void download(String filename, HttpServletResponse response) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
        OSSObject ossObject = ossClient.getObject(bucketName, filename);
        // 调用ossObject.getObjectContent获取文件输入流，可读取此输入流获取其内容。
        InputStream content = ossObject.getObjectContent();
        if (content != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            OutputStream outputStream=new ByteArrayOutputStream();
            response.setCharacterEncoding("UTF-8");
            while (true) {
                String line = reader.readLine();
                if (line == null) break;
                response.getWriter().write(line);
            }
            response.getWriter().close();
            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            content.close();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Override
    public void listFile() {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // ossClient.listObjects返回ObjectListing实例，包含此次listObject请求的返回结果。
        ObjectListing objectListing = ossClient.listObjects(bucketName);
        // objectListing.getObjectSummaries获取所有文件的描述信息。
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            System.out.println(" - " + objectSummary.getKey() + "  " +
                    "(size = " + objectSummary.getSize() + ")");
        }
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Override
    public void deleteFile(String fileUrl) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 删除文件。
        ossClient.deleteObject(bucketName, fileUrl);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase(".jpeg") || filenameExtension.equalsIgnoreCase(".jpg")
                || filenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (filenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase(".pptx") || filenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase(".docx") || filenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jeg";
    }
}
